// 第三步，目标表配置
$(document).ready(function() {
});

//清空第三步的表单信息
function resetTargetTableForm(){
	// 删除从表的目标行
	$("#targetTable tbody").empty();
	$('#targetTableForm input').val('');
}

//创建目标表的tr
// tableName：源数据表名
var srcTableName_id = "srcTableName_";
var srcTableId_name = "srcTableId_";
var srcTableDbLinkId_name = "srcTableDbLinkId_";
var srcTableDbUserName_name = "srcTableDbUserName_";
var targetTableDbLinkId_name = "targetTableDbLinkId_";
var targetTableId_name = "targetTableId_";
var targetTableName_name = "targetTableName_";
var targetTableVerifyButton_id = "buttonTargetTableVerify_";
var targetTableDbLinkIdCommboxTree_id = "targetTableDbLinkId_commbox_tree_";
var targetTableDbLinkIdTree_id = "targetTableDbLinkId_tree_";
var stColumnsRelation_id = "st_columns_relation_";
var canDataRecovery_name = "canDataRecovery_";

// tableName：源表名
// i：控件id|name的递增标识
// tableNames：表名控件，分表名
// columnsRelationPOList：源表与目标表的所有字段映射关系
// hasOkColumnsRelationPOList：读取的已经配置的字段映射关系
function newTargetTable(TargetTables, i){
	var srcTableName, srcTableDbLinkId, srcTableDbUserName, sourceDataId, targetDataId, tableNames, canDataRecovery, columnsRelationPOList, hasOkColumnsRelationPOLis;
	if(TargetTables == "undefind"){
		srcTableName = "tableName";
		srcTableDbLinkId = 0;
		srcTableDbUserName = "userName";
		sourceDataId = 0;
		targetDataId = 0;
		tableNames = [{type:'table',value:'table_name'}];
		canDataRecovery = 0;
	}else{
		srcTableName = TargetTables.srcTableName;
		srcTableDbLinkId = TargetTables.srcDbLinkId;
		srcTableDbUserName = TargetTables.srcDbUserName;
		sourceDataId = TargetTables.sourceDataId;
		targetDataId = TargetTables.targetDataId;
		tableNames = TargetTables.tableNames;
		columnsRelationPOList = TargetTables.columnsRelationPOList;
		hasOkColumnsRelationPOList = TargetTables.hasOkColumnsRelationPOList;
		canDataRecovery = TargetTables.canDataRecovery;
	}
	// 目标表tr
	var $tr = "";
	$tr += "<tr class='jqgrow' id='target_"+i+"'>";
	$tr += "<td style='width:18%' id='" + srcTableName_id + i + "'>";
	$tr += "<input type='text' value='" + sourceDataId + "' name='" + srcTableId_name + i + "' class='form-control hidden'/> ";
	$tr += "<input type='text' value='" + srcTableDbLinkId + "' name='" + srcTableDbLinkId_name + i + "' class='form-control hidden'/> ";
	$tr += "<input type='text' value='" + srcTableDbUserName + "' name='" + srcTableDbUserName_name + i + "' class='form-control hidden'/> ";
	$tr += srcTableName;
	$tr += "</td>";
	$tr += "<td style='width:72%'>";
	$tr += "<div class='form-horizontal'>";
	$tr += "<div class='subrow'>";
	$tr += "<label class='control-label col-sm-1'>数据库</label>";
	$tr += "<div class='col-sm-3'><input type='text' name='" + targetTableDbLinkId_name + i + "' class='form-control database-treecombo' data-rule='required' data-msg-required='数据库不能为空' readOnly='true' /></div>";
	$tr += "<label class='control-label col-sm-1 hidden'>目标表标识</label>";
	$tr += "<div class='col-sm-5 hidden'><input type='text' value='" + canDataRecovery + "' name='" + canDataRecovery_name + i + "' class='form-control' /></div>";
	$tr += "<div class='col-sm-5 hidden'><input type='text' value='" + targetDataId + "' name='" + targetTableId_name + i + "' class='form-control' /></div>";
	$tr += "<label class='control-label col-sm-1'>表名</label>";
	$tr += "<div class='col-sm-5'><input type='text' name='" + targetTableName_name + i + "' class='form-control tablename-plancombo' /></div>";
	$tr += "<button type='button' name='" + targetTableVerifyButton_id + i + "' class='btn btn-primary'>验证</button>";
	$tr += "</div>";
	$tr += "</div>";
	$tr += "</td>";
	$tr += "<td style='width:10%;text-align:center'><button type='button' id='" + stColumnsRelation_id + i + "' class='btn btn-primary btn-columns-ref'>字段映射</button></td>";
	$tr += "</tr>";
	$('#targetTable').append($tr);
	
	// 数据库（从表目标表），下拉树
	var $dbLinkIdTree = "";
	$dbLinkIdTree += "<div id='" + targetTableDbLinkIdCommboxTree_id + i + "' class='dropdown-list' style='position:absolute;display:none'>";
	$dbLinkIdTree += "<div id='" + targetTableDbLinkIdTree_id + i + "' class='ztree'></div>";
	$dbLinkIdTree += "</div>";
	$(document.body).append($dbLinkIdTree);
	
	// 数据库（从表目标表），下拉树
	bindDbLinkTree(targetTableDbLinkIdTree_id + i, targetTableDbLinkIdCommboxTree_id + i, targetTableDbLinkId_name + i, true);
	
	// 表名控件
	$('input[name="' + targetTableName_name + i + '"]').plancombobox({
		dataTextField : "name",
		dataValueField : "value",
		addMenuWidth:120,
		value: tableNames || [{type:'table',value:'table_name'}],
		addMenuSource:[{
            name:'固定变量',
            type:'val'
        },{
            name:'可变参数',
            type:'variable',
            panel:{
                url: webRoot+'/planmanage/addplan/jsp/variablePanel.tpl',
                render: function($extrMenu,source){
                	var tableName = JSON.stringify([{type: 'table',value: $('#' + srcTableName_id + i + '').text().trim()}]);
                	var dbLinkId = $('input[name="' + srcTableDbLinkId_name + i + '"]').val();
                	var dbUserName = $('input[name="' + srcTableDbUserName_name + i + '"]').val();
                	// var dbLinkId = $('input[name="' + targetTableDbLinkId_name + i + '"]').attr("vId");
                	// var dbUserName = $('input[name="' + targetTableDbLinkId_name + i + '"]').val();
                	$.blockUI({message : "数据载入中,请稍候..."});
                	$.ajax({
            			url : webRoot + 'baseconfig/dmsrctable/verifyTableName.do',
            			type : 'POST',
            			async : true,
            			data : {tableName: tableName, dbLinkId: dbLinkId, dbUserName: dbUserName, isEdit: isEdit}
            		}).done(function(serverData, textStatus, jqXHR) {
            			// 解析，参考主表字段，转换方法
            			if(act == "edit"){// 编辑
	            			var subRefCol, variableValue;
	            			for(var j = 0; j < tableNames.length; j++){
	            				if(tableNames[j].type == "variable"){
	            					subRefCol = tableNames[j].subRefCol;
	            					variableValue = tableNames[j].variableValue;
	            				}
	            			}
            			}
	                	$extrMenu.find('input[name="subRefCol"]').combobox({
	                		dataTextField : "columnName",
	                		dataValueField : "value",
	                		value : subRefCol,
	                		dataSource : serverData.allColumns
	                	});
	                	$extrMenu.find('input[name="subDefineValue"]').combobox({
	                		placeholder : "主表字段原值",
	                		dataTextField : "name",
	                		dataValueField : "value",
	                		value : variableValue || 0,
	                		dataSource : [ {
	                			name : "主表字段原值",
	                			value : 0
	                		}, {
	                			name : "年月",
	                			value : 2
	                		}, {
	                			name : "年月日",
	                			value : 3
	                		}, {
	                			name : "账期",
	                			value : 4
	                		}]
	                	});	
            		}).fail(function() {
            			fish.toast('error', '网络连接失败！');
            		}).always(function() {
            			$.unblockUI();
            		});
                },
                value:function($btn,value){
                	var $panel = $btn.data('extrMenu');
                    var subRefCol = $panel.find('input[name=subRefCol]').val();
                    var subDefineValue = $panel.find('input[name=subDefineValue]').val();
                    return subRefCol + ',' + subDefineValue;
                }
            }
        }]
	}).on('plancombobox:tablechange',function(e,vals){
		if(vals.newValue.length>50){
			fish.toast('warn', '表名不能超过50个字符');
			tableNameIsOK[$('.tablename-plancombo').index($(this))] = false;
		}else{
			tableNameIsOK[$('.tablename-plancombo').index($(this))] = true;
		}
		resetRefTableInfo($('.tablename-plancombo').index($(this)));
	});
	
	// 目标表名 验证 按钮事件
	$('button[name="' + targetTableVerifyButton_id + i + '"]').click(function() {
		// 源表数据
		var srcTableName = $('#' + srcTableName_id + i).text().trim();
		var srcDbLinkId = $('input[name="dbLinkId"]').attr("vId");
		var srcDbUserName = $('input[name="dbLinkId"]').val();
		// 目标表数据
		var tableName = $('input[name=' + targetTableName_name + i + ']').val();
		var dbLinkId = $('input[name="' + targetTableDbLinkId_name + i + '"]').attr("vId");
		var dbUserName = $('input[name="' + targetTableDbLinkId_name + i + '"]').val();
		var targetDataId = $('input[name="' + targetTableId_name + i + '"]').val();
		if(tableName == null || dbLinkId == null || dbUserName == null){
			fish.toast('warn', '请将目标表信息填写完整');
			return;
		}
		var index = i - 1;
		if(srcTableName.trim() == jQuery.parseJSON(tableName)[0].value && srcDbLinkId == dbLinkId&&srcDbUserName==dbUserName){
			fish.toast('warn', '目标表与源表不能相同，请重新输入表名或数据库');
			return;
		}
		$.blockUI({message : "数据载入中,请稍候..."});
		$.ajax({
			url : webRoot + 'baseconfig/dmtargettable/stColumnsRelation.do',
			type : 'POST',
			async : true,
			data : {tableName: tableName, dbLinkId: dbLinkId, dbUserName: dbUserName,
				srcTableName: srcTableName, srcDbLinkId: srcDbLinkId, srcDbUserName: srcDbUserName,
				targetDataId : targetDataId}
		}).done(function(serverData, textStatus, jqXHR) {
			if(serverData.sourceDataId == -3){
				fish.toast('warn', '该表不存在DM_TASK_ID和DM_DETAIL_ID这两个字段，请添加字段；若不添加该两个字段，则不提供数据恢复功能');
				return;
			} else if(serverData.sourceDataId == -1){// 表已经存在
				fish.toast('warn', '该表已经配置过，请重新输入表名');
				return;
			} else if(serverData.sourceDataId == -2){
				fish.toast('warn', '该表不存在，请重新输入表名');
				return;
			} else if (serverData.success == false) {
				fish.toast('error', serverData.msg);
				return;
			} else {// OK
				fish.toast('success', '该表可以使用');
			}
			return;
		}).fail(function() {
			fish.toast('error', '网络连接失败！');
		}).always(function() {
			$.unblockUI();
		});
	});
	
	// 字段映射
	//	targetColMap = ["PLAN_NAME,STRATEGY_NAME", "EFF_DATE,CONCURRENT_NUMBER", "STATE,STAFF_ID", "SOURCE_TYPE,null"];
	$.ajax(webRoot+'planmanage/addplan/jsp/table_ref.tpl?d'+new Date().getTime()).then(function (content) {
		$('#' + stColumnsRelation_id + i).click(function () {
			// 目标表数据
    		var targetTableName = $('input[name=' + targetTableName_name + i + ']').val();
    		var targetDbLinkId = $('input[name="' + targetTableDbLinkId_name + i + '"]').attr("vId");
    		var targetDbUserName = $('input[name="' + targetTableDbLinkId_name + i + '"]').val();
    		var targetDataId = $('input[name="' + targetTableId_name + i + '"]').val();
    		// 源表数据
			var tableName = $('#' + srcTableName_id + i).text().trim();
			var dbLinkId = $('input[name="' + srcTableDbLinkId_name + i +'"]').val();
			var dbUserName = $('input[name="' + srcTableDbUserName_name + i +'"]').val();
			if(tableName.trim() == jQuery.parseJSON(targetTableName)[0].value && dbLinkId == targetDbLinkId&&targetDbUserName==dbUserName){
				fish.toast('warn', '目标表与源表不能相同，请重新输入表名或数据库');
				return;
			}
			if(targetTableName == null || targetDbLinkId == null || targetDbUserName == null){
				fish.toast('warn', '请将目标表信息填写完整');
				return;
			}
			var me = this;
			// 验证目标表的是否可以配置
			$.blockUI({message : "数据载入中,请稍候..."});
			$.ajax({
				url : webRoot + 'baseconfig/dmtargettable/stColumnsRelation.do',
				type : 'POST',
				async : true,
				data : {tableName: targetTableName, dbLinkId: targetDbLinkId, dbUserName: targetDbUserName,
					srcTableName: tableName, srcDbLinkId: dbLinkId, srcDbUserName: dbUserName,
					targetDataId : targetDataId}
			}).done(function(serverData, textStatus, jqXHR) {
				$('input[name="' + canDataRecovery_name + i + '"]').val(1);
				if(serverData.sourceDataId == -3){
					fish.toast('warn', '该表不存在DM_TASK_ID和DM_DETAIL_ID这两个字段，请添加字段；若不添加该两个字段，则不提供数据恢复功能');
					$('input[name="' + canDataRecovery_name + i + '"]').val(0);
					// return;
				} else if(serverData.sourceDataId == -1){// 表已经存在
					fish.toast('warn', '该表已经配置过，请重新输入表名');
					return;
				} else if(serverData.sourceDataId == -2){
					fish.toast('warn', '该表不存在，请重新输入表名');
					return;
				}
				var index = i + 0;
				var rowId = $('.btn-columns-ref').index($(me));
				// 显示字段映射控件
				var $dialog;
				var tpl = '<div class="ui-dialog panel panel-default"><div class="modal-header">表映射</div>';
				tpl += '<span class="close text-muted glyphicon glyphicon-remove"></span>';
				tpl += '<div class="panel-body">';
				tpl += '</div>';
				tpl += '</div>';
				$dialog = $(tpl).appendTo('body');
				$dialog.append(content);
				var $close = $dialog.find('.close');
				var $closeBtn = $dialog.find('.pop-close');
				$dialog.dialog({
					canClose:false,
					show:true,
					width:800,
					hide:true,
					modal: true
				});
				$close.click(function(){
					$dialog.dialog('close').remove();
				});
				$closeBtn.click(function(){
					$dialog.dialog('close').remove();
				});
	        	if(act == "edit" && targetColMaps[rowId] && columnsRelationsIsOK[rowId] != 3){
	        		stColumnsRelation(rowId, $dialog, index, columnsRelationPOList, i, hasOkColumnsRelationPOList);
	        	}else{
		    		$.ajax({
						url : webRoot + 'baseconfig/dmsrctable/stColumnsRelation.do',
						type : 'POST',
						async : true,
						data : {tableName: tableName, dbLinkId: dbLinkId, dbUserName: dbUserName,
							subTableName: targetTableName,  subDbLinkId: targetDbLinkId, subDbUserName: targetDbUserName}
					}).done(function(serverData, textStatus, jqXHR) {
						stColumnsRelation(rowId, $dialog, index, serverData, i);
					}).fail(function() {
						fish.toast('error', '网络连接失败！');
					}).always(function() {
						$.unblockUI();
					});
	        	}
				return;
			}).fail(function() {
				fish.toast('error', '网络连接失败！');
			}).always(function() {
				$.unblockUI();
			});
		});

	});
}

// 字段映射
function stColumnsRelation(rowId, dialog, index, serverData, i, hasOkColumnsRelationPOList){
	if(serverData[0].src == "-2"){// 源表不存在
		fish.toast('warn', '源表不存在，请重新配置源表');
		return;
	}
	if(serverData[0].target == "-2"){// 目标表不存在
		fish.toast('warn', '目标表不存在，请重新配置目标表');
		return;
	}
	var $refGrid, $srcGgrid;
	var sourceData = [],src,target,result = [];
	$('.pop-submit').click(function (message) {
		var dels = [],i=0;
		for(var k in targetColMaps){
			if(targetColMaps[k][0]==index){
				dels.push(k);
			}
		}
		for(i=0;i<dels.length;i++){
			delete targetColMaps[dels[i]];
		}
		var rs = [];
		rs.push(index);
		for(var key in result){
			if(key.indexOf('_@TYPE')==-1){
				var _key = key.substring(0,key.indexOf('_@VALUE'));
				rs.push(result[_key+'_@TYPE']+','+result[_key+"_@VALUE"]);
			}
		};
		var flag = true;
		$refGrid.find('input').each(function(){
			if($(this).val().trim().length==0){
				flag = false;
				fish.toast('warn', '映射验证不通过，目标表字段需要输入目标字段映射');
				return false;
			}
		});
		var refDatas = $refGrid.grid('getRowData');
		var srcDatas = $srcGgrid.grid('getRowData');
		var targetCount = 0;
		for(var i=0;i<srcDatas.length;i++){
			if(srcDatas[i].target!=null){
				targetCount++;
			}
		}
		if(targetCount>refDatas.length){
			flag = false;
			fish.toast('warn', '映射验证不通过，目标表字段没有完全映射完毕');
		}
		if(flag){
			if(columnsRelationsIsOK[index - 1] == 2){// 新增的从表
				columnsRelationsIsOK[index - 1] = 3;
			}else{
				columnsRelationsIsOK[index - 1] = 1;
			}
			targetColMaps[rowId] = rs;
			dialog.dialog('close').remove();
		}
	});
	var opt = {
		data: sourceData,
		height:300,
		colModel: [{
			name: 'src',
			label: '源',
			align:'center',
			formatter:function(val){
				if(!val)return '';
				return '<div class="form-inline">' +
					'<div class="col-sm-10 srcclass">' +
					val+
					'</div><div class="col-sm-2 glyphicon glyphicon-ok srcclassicon" style="padding-right: 5px;font-size: 12px;color: green;display: none"></div>' +
					'</div>';
			}
		},  {
			name: 'target',
			label: '目标',
			align:'center',
			key:true,
			title: false, //内容没有提示
			formatter:function(val){
				if(!val)return '';
				if(result[val+"_@VALUE"]){
					return '<div style="color: #808080;margin-right: 26px;">'+val+'</div>';
				}
				return '<div class="form-inline">' +
					'<div class="col-sm-10 targetclass" style="color: red;">' +
					val+
					'</div><div class="col-sm-2 glyphicon glyphicon-ok targetclassicon" style="padding-right: 5px;font-size: 12px;color: green;display: none"></div>' +
					'</div>';
			}
		}],
		onCellSelect: function (e,rowid, iCol, cellcontent) {//选中单元格的事件
			if(iCol==0){
				var srcicon = $(e.originalEvent.target).parent().find('.srcclassicon');
				var display = srcicon.css('display');
				$('.srcclassicon').hide();
				if(display=='none'){
					srcicon.show();
					src = rowid;
				}
				else{
					src = null;
				}
			}
			else{
				var targeticon = $(e.originalEvent.target).parent().find('.targetclassicon');
				var display = targeticon.css('display');
				$('.targetclassicon').hide();
				if(display=='none'){
					targeticon.show();
					$('#addPerf').removeClass('disabled');
					target = rowid;
				}
				else{
					$('#addPerf').addClass('disabled');
				}
			}
		}
	};
	$srcGgrid = $("#srcGgrid").grid(opt);
	var refData = [];
	var opt = {
		data: refData,
		height:300,
		autoencode:true,
		colModel: [ {
			name: 'ref',
			label: '映射关系',
			align: "center",
			key:true,
			formatter:function(val,cellMode,cells){
				val = val.split(',');
				if(cells.type!='INPUT_'){//!fish.isUndefined(val[0])&&val[0]!='undefined'
					return val[0] + '---->' + val[1];
				}
				else{
					var target =cells.srcValue,targetValue = cells.targetValue;
					if(fish.isUndefined(target)||target=='undefined'){
						target = val[1];
						targetValue = '';
					}
					return '<div class="form-inline">' +
						'<div class="col-sm-6">' +
						'<span style="">'+target+'</span>填写值：' +
						'</div><div class="col-sm-6">' +
						'<input class="form-control" name="'+target+'" style="width:100%;height:20px;" type="text" value="'+targetValue+'"/>' +
						'</div>'+
						'</div>';
				}
			}
		},
		{
			label: '操作',
			width:20,
			name: 'action',
			formatter: function(){
				return '<div class="glyphicon glyphicon-remove-circle" style="padding-left: 8px;font-size: 15px;color: #ff0000;cursor: pointer;"></div>';
			}
		}],
		onCellSelect: function (e,rowid, iCol, cellcontent) {//选中单元格的事件
			if(iCol==1){
				var data = $refGrid.grid('getRowData',rowid);
				var targetKey = data.targetValue;
				if(data.type=='INPUT_'&&data.srcValue!=null){
					targetKey = data.srcValue;
				}
				delete result[targetKey+"_@VALUE"];
				delete result[targetKey+"_@TYPE"];
				$refGrid.grid('delRow',rowid);
				$refGrid.grid('delRowData',rowid);
				$srcGgrid.grid('setCell',targetKey,'target',targetKey);
			}
		}
	};

	$refGrid = $("#refGrid").grid(opt);
	var reOpen = false;
	for(var key in targetColMaps){
		// if(parseInt(targetColMaps[key][0])==index && key == i-1){break;}
		if(parseInt(targetColMaps[key][0])==index){
			refData = [];
			for(var j=1;j<targetColMaps[key].length;j++){
				var data = targetColMaps[key][j].split(',');
				refData.push({ref:data[1]+','+data[2],type:data[0],srcValue:data[1],targetValue:data[2],target:data[2]});
				var targetValue = data[2];
				if(data[0]=='INPUT_'){
					targetValue = data[1];
				}
				result[targetValue+"_@VALUE"]=data[1]+','+data[2];
				result[targetValue+'_@TYPE']=data[0];

			}
			$refGrid.grid("addRowData",refData);

			$refGrid.find('input').blur(function(){
				var name = $(this).attr('name');
				result[name+"_@VALUE"]=name+','+$(this).val();
			});
			reOpen = true;
		}
	}
	// 把相同的字段映射到右边
	if(!reOpen){
		var refData = [];
		// 判断是不是编辑
		if(act == "edit" && targetColMaps[rowId]){
			refData = hasOkColumnsRelationPOList;
			for(var j = 0;j<hasOkColumnsRelationPOList.length;j++){
//				refData.push({type:'NORMAL_',ref:hasOkColumnsRelationPOList[j].src+","+hasOkColumnsRelationPOList[j].src,srcValue:hasOkColumnsRelationPOList[j].src,targetValue:hasOkColumnsRelationPOList[j].target,target:hasOkColumnsRelationPOList[j].target});
				result[hasOkColumnsRelationPOList[j].src+"_@VALUE"]=hasOkColumnsRelationPOList[j].src+","+hasOkColumnsRelationPOList[j].target;
				result[hasOkColumnsRelationPOList[j].src+'_@TYPE'] = hasOkColumnsRelationPOList[j].type;
			}
		}else{
			for(var j = 0;j<serverData.length;j++){
				if(serverData[j].src == serverData[j].target && 
						serverData[j].srcDateType == serverData[j].targetDateType && 
						serverData[j].srcColumnSize <= serverData[j].targetColumnSize){// 判断是否可以自动匹配的条件：字段名称、字段类型、字段长度
					refData.push({type:'NORMAL_',ref:serverData[j].src+","+serverData[j].src,srcValue:serverData[j].src,targetValue:serverData[j].src,target:serverData[j].src});
					result[serverData[j].src+"_@VALUE"]=serverData[j].src+","+serverData[j].src;
					result[serverData[j].src+'_@TYPE'] = 'NORMAL_';
				}
			}
		}
		$refGrid.grid("addRowData", refData);
		$refGrid.find('input').blur(function(){
			var name = $(this).attr('name');
			result[name+"_@VALUE"]=name+','+$(this).val();
		});
	}
	$srcGgrid.grid("addRowData", serverData);
	$('#addPerf').click(function(){
		if($(this).hasClass('disabled'))return;
		var srcDateType = $srcGgrid.grid('getRowData',src).srcDateType;
		var targetDateType = $srcGgrid.grid('getRowData',target).targetDateType;
		var srcColumnSize = $srcGgrid.grid('getRowData',src).srcColumnSize;
		var targetColumnSize = $srcGgrid.grid('getRowData',target).targetColumnSize;
		if(typeof(srcDateType) != "undefined" && typeof(srcColumnSize) != "undefined"){
			if(srcDateType != targetDateType || srcColumnSize > targetColumnSize){
				fish.toast('warn', '源、目标字段类型不匹配或者源字段长度大于目标字段长度，请重新选择');
				return;
			}
		}
		var srcValue = $srcGgrid.grid('getRowData',src).src;
		var targetValue = $srcGgrid.grid('getRowData',target).target;
		var val = srcValue+','+targetValue;
		var type = 'INPUT_';
		if(!fish.isUndefined(srcValue)&&srcValue!='undefined'){
			type = 'NORMAL_';
		}
		if(!result[targetValue+"_@VALUE"]) {
			$refGrid.grid('addRowData', [{
				ref: val,
				srcValue:srcValue,
				targetValue:targetValue,
				type:type,
				target:target
			}]);
			result[targetValue+"_@VALUE"]=val;
			result[targetValue+'_@TYPE']=type;
			$refGrid.find('input').blur(function(){
				var name = $(this).attr('name');
				result[name+"_@VALUE"]=name+','+$(this).val();
			});
			$srcGgrid.grid('setCell',target,'target',targetValue);
		}
	});
}

// 获取表单数据-目标数据信息
function getTargetTableFormData(){
	// 解析参数
	var targetTables = new Array();
	var targetTable;
	var srcTableNames = [];
	var targetTableNames = [];
	var targetTableDbLinkIds = [];
	for (var i = 1; i <= tableNum; i++) {
		// 拼接一个目标表的数据，用于传到后台
		var srcTableName = $("#" + srcTableName_id + i + "").text().trim();
		var srcTableId = $("input[name=" + srcTableId_name + i + "]").val();
		var srcDbLinkId = $('input[name="' + srcTableDbLinkId_name + i +'"]').val();
		var srcDbUserName = $('input[name="' + srcTableDbUserName_name + i +'"]').val();
		var targetTableId = $("input[name=" + targetTableId_name + i + "]").val();
		var targetTableName = $("input[name=" + targetTableName_name + i + "]").plancombobox('value');
		var targetTableDbLinkId = $("input[name=" + targetTableDbLinkId_name + i + "]").attr("vId");
		var targetDbUserName = $("input[name=" + targetTableDbLinkId_name + i + "]").val();
		var canDataRecovery = $('input[name="' + canDataRecovery_name + i + '"]').val();
		if(typeof(targetTableName) != "undefined" && typeof(targetTableDbLinkId) != "undefined"){
			targetTable = {targetDataId: targetTableId, sourceDataId: srcTableId, srcTableName: srcTableName, srcDbUserName: srcDbUserName,
					srcDbLinkId: srcDbLinkId, targetTableName: targetTableName, targetTableDbLinkId: targetTableDbLinkId, 
					targetDbUserName: targetDbUserName, canDataRecovery: canDataRecovery};
			targetTables.push(targetTable);
		}
	}
	for(var k in delSubTableIds){
		if(delSubTableIds[k] != null && delSubTableIds[k] != ""){
			targetTable = {sourceDataId: delSubTableIds[k], isDelete: 1};
			targetTables.push(targetTable);
		}
	}
	// 判断有没有相同的目标表
	for(var i = 0; i < targetTables.length; i++){
		for(var j = i + 1; j < targetTables.length; j++){
			if(targetTables[i].isDelete == 1 || targetTables[j].isDelete == 1){
				continue;
			}
			if(jQuery.parseJSON(targetTables[i].targetTableName)[0].value.toLowerCase() == jQuery.parseJSON(targetTables[j].targetTableName)[0].value.toLowerCase() && 
					targetTables[i].targetTableDbLinkId == targetTables[j].targetTableDbLinkId){
				return false;
			}
		}
	}
	// 表单数据
	targetTableFormData.targetTableStr = JSON.stringify(targetTables);
	targetTableFormData.targetColMaps = JSON.stringify(targetColMaps);
	targetTableFormData.staffId = staffId;
	targetTableFormData.dmStrategyId = dmStrategyId;
	return true;
}
